import { wsEndpoint, wsEndpoint_rizhi, wsEndpointNew } from 'api';
import { deepEqual } from 'helpers/object';
import { memo, useEffect } from 'react';
import {
  useRecoilState,
  useRecoilValue,
  useResetRecoilState,
  useSetRecoilState
} from 'recoil';
import io from 'socket.io-client';
import { w3cwebsocket as WebSocketClient } from 'websocket';
import { v4 as uuidv4 } from 'uuid';
import { useAuth } from 'hooks/auth';

import { IAction, actionState } from 'state/action';
import { IUserinfo, userState } from 'state/auth0State';
import {
  IMessage,
  IMessageUpdate,
  IToken,
  askUserState,
  chatSettingsState,
  chatSettingsValueState,
  loadingState,
  voicingState,
  messagesState,
  sessionState,
  sessionState_rizhi,
  msgState,
  tokenCountState,
  messagesStatusState
} from 'state/chat';
import { clientState } from 'state/client';
import {
  IElement,
  avatarState,
  elementState,
  tasklistState
} from 'state/element';
import { projectSettingsState } from 'state/project';
import { sessionIdState, userEnvState } from 'state/user';
import { TFormInput } from './organisms/FormInput';
import { isRenderingState, promtStringState, initWAKEUP_NTF } from 'state/chat';

const compareMessageIds = (a: IMessage, b: IMessage) => {
  if (a.id && b.id) return a.id === b.id;
  return false;
};

export default memo(function Socket() {
  const pSettings = useRecoilValue(projectSettingsState);
  const { accessToken, authenticating } = useAuth();
  const userEnv = useRecoilValue(userEnvState);
  const setLoading = useSetRecoilState(loadingState);
  const setVoicing = useSetRecoilState(voicingState);
  const setPromtString = useSetRecoilState(promtStringState);
  const setMsgId = useSetRecoilState(msgState);
  const setMessageStatus = useSetRecoilState(messagesStatusState);
  const sessionId = useRecoilValue(sessionIdState);
  const [session, setSession] = useRecoilState(sessionState);
  const [session_rizhi, setSession_rizhi] = useRecoilState(sessionState_rizhi);
  const setMessages = useSetRecoilState(messagesState);
  const setTokenCount = useSetRecoilState(tokenCountState);
  const setAskUser = useSetRecoilState(askUserState);
  const setElements = useSetRecoilState(elementState);
  const setAvatars = useSetRecoilState(avatarState);
  const setTasklists = useSetRecoilState(tasklistState);
  const setActions = useSetRecoilState(actionState);
  const setChatSettings = useSetRecoilState(chatSettingsState);
  const resetChatSettingsValue = useResetRecoilState(chatSettingsValueState);
  const setUser = useSetRecoilState(userState);
  const [isRendering, setIsRendering] = useRecoilState(isRenderingState);

  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  const sid = urlParams.get('sid') ?? '';
  const client = useRecoilValue(clientState);

  // var W3CWebSocket = require('websocket').w3cwebsocket;

  let signNum = 0;


  const handleStopRendering = () => {
    setLoading(false);
    setIsRendering(false);
    // 打断数字人讲话，等待中
    setVoicing('event_vad_end');
    // 触发数字人讲话[停止说话]
    client.setAISay('', 'task_stop', session.socket);
    // const lastIndex = messages.findLastIndex(obj => obj.parentId === null);
    // let message: IMessage
    // 如果找到符合条件的对象，则为其添加show: true属性
    // if (lastIndex !== -1) {
    //     message = messages[lastIndex]
    //     message.stopRendering = true
    //     setMessages((oldMessages) => {
    //        return [
    //             ...oldMessages.slice(0, lastIndex),
    //             message,
    //             ...oldMessages.slice(lastIndex + 1)
    //           ]
    //     })
    // }
    // session?.socket.emit('stop');
    // session?.socket.emit('stop');

  };

  function getCurrentDateTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  // 用于计算十秒倒计时的变量，当唤醒后10秒没有其他动作，识别中图片小时
  let numInit = 0;
  let interValInit: string | number | NodeJS.Timeout | undefined;
  // 用于接收每次收到的收声消息
  let msgInit = {};
  useEffect(() => {
    // 模拟我收到一个声音
    // setTimeout(() => {
    //   setMessageStatus('awakened');
    //   document.getElementsByClassName('overScroll')[0].style.height = document.getElementsByClassName('1111')[0].scrollHeight - 20 + 'px';
    //   setMessageStatus('finish');
    //   setPromtString('介绍一下新建元');
    //   console.log(getCurrentDateTime());
    //   initWAKEUP_NTF.num = initWAKEUP_NTF.num + 1;
    // }, 8000);
    if (session?.socket) {
      return;
    }
    // @ts-ignore
    const socket = new WebSocketClient(wsEndpointNew);

    setSession({
      socket
    });
    // const socket_rizhi = new WebSocketClient(wsEndpoint_rizhi);
    // setSession_rizhi({
    //   socket_rizhi
    // });
    let msgFromJQR = '';
    socket.onopen = () => {
      console.log('WebSocket连接已建立');
    };
    // socket_rizhi.onopen = () => {
    //   // 日志的socket创建
    //   console.log('WebSocket_rizhi连接已建立');
    // };
    socket.onmessage = (message: any) => {
      try {
        let msg = (message.data && JSON.parse(message.data)) || {};
        msgInit = msg;
        //日志
        let now_time = getCurrentDateTime();
        // socket_rizhi.send('数字人ID:' + urlParams.get('shuziren') + ' 收声接收信息时间：' + now_time + '，内容：' + JSON.stringify(msg)); // 发送一条日志消息
        console.log('socket返回信息时间：' + now_time + '，内容：' + JSON.stringify(msg));
        setMsgId(msg.msg_id);
        // 接受问题
        if (msg.msg_id == 'SPEECH_ISR_ONLY_RESULT_NTF') {
          // msgFromJQR +=msg.text;

          if (msg.isLast) {
            // 这里有20的padding,所以要减去20，用于思考中等等图片出现时防止滚动条跳动的
            document.getElementsByClassName('overScroll')[0].style.height = document.getElementsByClassName('1111')[0].scrollHeight - 20 + 'px';

            setMessageStatus('finish');
            // 发送给数字人
            setPromtString(msg.text);
            // msgFromJQR = ""
          } else {
            setMessageStatus('inProgress');
          }
        }
        // 接受激活
        if (msg.msg_id == 'SPEECH_ISR_WAKEUP_NTF') {
          // 只要激活就让对比的数字加一
          initWAKEUP_NTF.num = initWAKEUP_NTF.num + 1;
          setMessageStatus('awakened');
          clearInterval(interValInit);
          numInit = 0;
          interValInit = setInterval(() => {
            numInit++;
            if (numInit >= 10) {
              // 如果十秒后，作为收声的对象中不存在isLast属性，将识别中图片隐藏
              if (!msgInit.hasOwnProperty('isLast')) {
                numInit = 0;
                setMessageStatus('finish');
                // 停止计时器，初始化计时时间
                clearInterval(interValInit);

              }
            }

          }, 1000);
          // const audio = new Audio();
          // audio.src = 'assets/我在.wav';
          // audio.volume = 1;
          // 数字人应答一下
          // handleStopRendering();

          setLoading(false);
          setIsRendering(false);
          // 打断数字人讲话，等待中
          setVoicing('event_vad_end');
          // 触发数字人讲话[停止说话]
          socket.send(`{text: "", status: "task_stop"}`);
          socket.send(`{text: "我在。", status: "stream_token"}`);
          socket.send(`{text: "", status: "stream_end"}`);

          socket.send(`{"msg_id":"SPEECH_ISR_START_REQ"}`);
          // if(signNum==0){
          //   audio.play();
          //   // client.setAISay('我在','stream_token')
          // }else{
          //   // client.setAISay('我在','stream_token')
          //   audio.play();
          // }
          // signNum++

          // audio.currentTime = 0
          // audio.pause()
          // client.setAISay('','stream_end')
        }
      } catch (error) {

      }
    };
  }, [userEnv, authenticating, pSettings]);
  return null;
});
